<template>
  <el-row>
    <el-col :span="5">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree
              :option="treeOption"
              :data="treeData"
              @node-click="nodeClick"
            />
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="19">
      <basic-container>
        <avue-crud
          :option="option"
          :search.sync="search"
          :table-loading="loading"
          :data="data"
          ref="crud"
          v-model="form"
          :permission="permissionList"
          @row-del="rowDel"
          @row-update="rowUpdate"
          @row-save="rowSave"
          :before-open="beforeOpen"
          :page.sync="page"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
        >
          <template slot="menuLeft">
            <el-button
              type="danger"
              size="small"
              plain
              icon="el-icon-delete"
              v-if="permission.user_delete"
              @click="handleDelete"
              >删 除
            </el-button>
            <!-- <el-button type="success"
                       size="small"
                       plain
                       v-if="permission.user_import"
                       icon="el-icon-upload2"
                       @click="handleImport">导入
            </el-button>
            <el-button type="warning"
                       size="small"
                       plain
                       v-if="permission.user_export"
                       icon="el-icon-download"
                       @click="handleExport">导出
            </el-button> -->
          </template>
        </avue-crud>
        <el-dialog
          title="用户数据导入"
          append-to-body
          :visible.sync="excelBox"
          width="555px"
        >
          <avue-form
            :option="excelOption"
            v-model="excelForm"
            :upload-after="uploadAfter"
            :upload-delete="uploadDelete"
          >
            <template slot="excelTemplate">
              <el-button type="primary" @click="handleTemplate">
                点击下载<i class="el-icon-download el-icon--right"></i>
              </el-button>
            </template>
          </avue-form>
        </el-dialog>
      </basic-container>
    </el-col>
  </el-row>
</template>

<script>
import {
  getList,
  getDetail,
  remove,
  save,
} from "@/api/rb-oem/taxCategory/tax_product";
import { getLazyList } from "@/api/rb-oem/taxCategory/tax_category";
import { getRole, grantTree, getRoleTree } from "@/api/system/role";
// import {getPostList} from "@/api/system/post";
// import {validatenull} from "@/util/validate";
import { mapGetters } from "vuex";
import website from "@/config/website";
import { getToken } from "@/util/auth";

export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      form: {},
      menuTreeObj: [], //用户已有菜单权限数据
      openType: "", //打开dialog弹框的类型
      search: {},
      excelBox: false,
      initFlag: true,
      selectionList: [],
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      init: {
        roleTree: [],
        deptTree: [],
      },
      props: {
        label: "categoryName",
        value: "categoryNo",
        disabled: this.isDisabledFn,
      },
      parentCategoryNo: "",
      treeData: [],
      treeOption: {
        nodeKey: "id",
        lazy: true,
        treeLoad: function (node, resolve) {
          const parentCategoryNo = node.level === 0 ? 0 : node.data.categoryNo;
          getLazyList(parentCategoryNo).then((res) => {
            resolve(
              res.data.data.map((item) => {
                return {
                  ...item,
                  leaf: !item.hasChildren,
                };
              })
            );
          });
        },
        addBtn: false,
        menu: false,
        size: "small",
        props: {
          labelText: "标题",
          label: "categoryName",
          value: "categoryNo",
          children: "children",
        },
      },
      option: {
        height: "auto",
        calcHeight: 80,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        selection: true,
        viewBtn: true,
        delBtn: false,
        display: true,
        // dialogType: 'drawer',
        dialogClickModal: false,
        column: [
          {
            label: "分类名称",
            prop: "categoryName",
            type: "input",
            display: false,
            minWidth: 150,
            rules: [
              {
                required: true,
                message: "请输入分类名称",
                trigger: "blur",
              },
            ],
          },
          {
            label: "商品和税收分类合并编码",
            prop: "taxNo",
            type: "input",
            minWidth: 180,
            labelWidth: 180,
            rules: [
              {
                required: true,
                message: "请输入商品和税收分类合并编码",
                trigger: "blur",
              },
            ],
          },
          {
            label: "商品名称",
            prop: "taxProductName",
            type: "input",
            minWidth: 150,
            rules: [
              {
                required: true,
                message: "请输入商品名称",
                trigger: "blur",
              },
            ],
          },
          {
            label: "税率(%)",
            prop: "taxRate",
            type: "number",
            minWidth: 150,
            rules: [
              {
                required: true,
                message: "请输入税率",
                trigger: "blur",
              },
            ],
          },
          {
            label: "简称",
            prop: "taxShortName",
            type: "input",
            minWidth: 150,
            rules: [
              {
                required: true,
                message: "请输入简称",
                trigger: "blur",
              },
            ],
          },
          {
            label: "关键字",
            prop: "taxKeyName",
            type: "input",
            minWidth: 150,
            rules: [
              {
                required: true,
                message: "请输入关键字",
                trigger: "blur",
              },
            ],
          },
          {
            label: "描述",
            prop: "description",
            type: "input",
            minWidth: 150,
            rules: [
              {
                required: true,
                message: "请输入描述",
                trigger: "blur",
              },
            ],
          }
        ],
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/blade-user/import-user",
          },
          {
            label: "数据覆盖",
            prop: "isCovered",
            type: "switch",
            align: "center",
            width: 80,
            dicData: [
              {
                label: "否",
                value: 0,
              },
              {
                label: "是",
                value: 1,
              },
            ],
            value: 0,
            slot: true,
            rules: [
              {
                required: true,
                message: "请选择是否覆盖",
                trigger: "blur",
              },
            ],
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  watch: {
    "excelForm.isCovered"() {
      if (this.excelForm.isCovered !== "") {
        const column = this.findObject(this.excelOption.column, "excelFile");
        column.action = `/api/blade-user/import-user?isCovered=${this.excelForm.isCovered}`;
      }
    },
  },
  computed: {
    ...mapGetters(["permission"]),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  mounted() {},
  methods: {
    nodeClick(data) {
      this.parentCategoryNo = data.categoryNo;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    rowSave(row, done, loading) {
      if (!this.parentCategoryNo) {
        this.$message({
          type: "error",
          message: "请选择上级分类!",
        });
      }
      save(Object.assign(row, { categoryNo: this.parentCategoryNo })).then(
        () => {
          this.initFlag = false;
          // this.$refs.crud.resetForm()
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      save(row).then(
        () => {
          this.initFlag = false;
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    searchReset() {
      this.query = {};
      this.parentCategoryNo = "";
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleImport() {
      this.excelBox = true;
    },
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    uploadDelete() {
      return this.$confirm("是否确定移除该选项？");
    },
    handleExport() {
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/blade-user/export-user?${
            this.website.tokenHeader
          }=${getToken()}&account=${this.search.account}&realName=${
            this.search.realName
          }`
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/blade-user/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    /**
     * @func dialog打开回调
     * @desc 监听回调类型，调取接口，处理逻辑
     * @param {Function} done - 回调完成
     * @param {String} type - 打开类型
     * */
    beforeOpen(done, type) {
      this.openType = type;
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
        // const column = this.findObject(this.option.group, "userType");
        // column.disabled = true;
      } else {
      }
      this.initFlag = true;
      done();
    },
    /**
     * @func 菜单权限树形是否禁止
     * @desc dialog打开类型为 view 则禁止权限树
     * @param {String} openType - 打开类型
     * */
    isDisabledFn() {
      const _this = this;
      if (["view"].includes(_this.openType)) {
        return true;
      }
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (!this.parentCategoryNo) {
        this.parentCategoryNo = '';
      }
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query),
        this.parentCategoryNo
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>

<style>
.box {
  height: 800px;
}

.el-scrollbar {
  height: 100%;
}

.box .el-scrollbar__wrap {
  overflow: scroll;
}
</style>
